﻿import QtQuick 2.15
import QtQuick.Controls
import QtQuick.Controls.Basic
import FilUI

// 导入自定义控件库
import "../controls"

Rectangle {
    id: control
    objectName: "LoginPage"
    width: 544
    height: 320 - 30
    // border.color: "#fff0e5"
    radius: 30

    // var
    property string user_name                   : ""
    property string user_password               : ""
    property string user_weburl                 : ""
    property bool remember_pwd                  : false
    property bool autologon                     : false

    // signal
    signal loginSucceed()

    // theme
    color: "#fff4f1"

    // Title
    Rectangle {
        id: title_text
        width: parent.width
        height: 40
        anchors.horizontalCenter: parent.horizontalCenter
        radius: parent.radius
        color: "transparent" //parent.color
        Text {
            text: "" //qsTr("Login")
            color: "#595959"
            anchors.centerIn: parent
            font.pointSize: 18
        }
    }

    // input
    Rectangle {
        anchors.top: title_text.bottom
        id: input_text_group
        width: parent.width
        height: 120
        color: "transparent" //parent.color
        Column {
            anchors.centerIn: parent
            Rectangle {
                width: input_text_group.width / 2
                height: input_text_group.height / 3
                color: input_text_group.color
                FilTextBox {
                    id: id_filtextbox__user
                    width: parent.width
                    height: parent.height - 8
                    placeholderText: qsTr("User")
                    anchors.centerIn: parent
                    background: Rectangle {
                        anchors.fill: parent
                        radius: 8
                        // border.color: "#fff4f1"
                        // border.width: 2
                    }
                    color: "#595959"
                    onTextChanged: control.user_name = text
                }
            }
            Rectangle {
                width: input_text_group.width / 2
                height: input_text_group.height / 3
                color: input_text_group.color
                FilPasswordBox {
                    id: id_filtextbox__password
                    width: parent.width
                    height: parent.height - 8
                    placeholderText: qsTr("Password")
                    anchors.centerIn: parent
                    background: Rectangle {
                        anchors.fill: parent
                        radius: 8
                        // border.color: "#fff4f1"
                        // border.width: 2
                    }
                    color: "#595959"
                    onTextChanged: control.user_password = text
                }
            }
            Rectangle {
                width: input_text_group.width / 2
                height: input_text_group.height / 3
                color: input_text_group.color
                FilTextBox {
                    id: id_filtextbox__weburl
                    width: parent.width
                    height: parent.height - 8
                    placeholderText: qsTr("Website")
                    anchors.centerIn: parent
                    background: Rectangle {
                        anchors.fill: parent
                        radius: 8
                        // border.color: "#fff4f1"
                        // border.width: 2
                    }
                    color: "#595959"
                    onTextChanged: control.user_weburl = text
                }
            }
        }
    }

    Rectangle {
        id: checkbox_group
        property alias savePassword: id_filcheckbox__pwd.checked
        property alias saveAutoLogin: id_filcheckbox__auto.checked
        width: parent.width
        height: 28
        anchors.top: input_text_group.bottom
        color: "transparent" // parent.color
        Row {
            anchors.centerIn: parent
            FilCheckBox {
                id: id_filcheckbox__pwd
                checked: checkbox_group.savePassword
                text: qsTr("Rememb")
                anchors.verticalCenter: parent.verticalCenter
            }
            Rectangle {
                height: checkbox_group.height
                width: 50
                color: checkbox_group.color
                anchors.verticalCenter: parent.verticalCenter
            }
            FilCheckBox {
                id: id_filcheckbox__auto
                checked: checkbox_group.saveAutoLogin
                text: qsTr("Autologon")
                anchors.verticalCenter: parent.verticalCenter
            }
        }
        onSavePasswordChanged: {
            // 当“记住密码”取消勾选时需要自动取消勾选“自动登录”，防止自动登录时密码是空的
            if (savePassword === false) {
                if (saveAutoLogin === true) {
                    saveAutoLogin = false
                }
            }
        }
        onSaveAutoLoginChanged: {
            // 当“自动登录”被勾选时需要自动勾选“记住密码”，防止自动登录时密码是空的
            if (saveAutoLogin === true) {
                if (savePassword === false) {
                    savePassword = true
                }
            } else {
                SettingsHelper.saveAutoLogin(saveAutoLogin)
            }
        }
    }

    Item {
        id: login_button
        width: parent.width
        height: 50
        anchors.top: checkbox_group.bottom
        // FilRadiusButton {
        //     height: parent.height - 8
        //     width: parent.width / 2
        //     anchors.centerIn: parent
        //     text: "登录"
        //     // pointSize: 12
        //     loading: true
        // }
        FilRadiusButtonn {
            id: id_filradiusbuttonn__login
            height: parent.height - 8
            width: parent.width / 2
            anchors.centerIn: parent
            ringDiameter: 18
            font.pointSize: 12
            // loading: true
            onClicked: {
                if (AppInfo.debugEnable) {
                    loginInfoSave()
                    loginSucceed()
                } else {
                    text_login_status.text = ""
                    login(user_name, user_password, user_weburl)
                }
            }
            state: "idle"
            states: [
                State {
                    name: "idle"
                    PropertyChanges {
                        id_filradiusbuttonn__login.text: qsTr("Login")
                        id_filradiusbuttonn__login.loading: false
                    }
                },
                State {
                    name: "logging"
                    PropertyChanges {
                        id_filradiusbuttonn__login.text: qsTr("Logging")
                        id_filradiusbuttonn__login.loading: true
                    }
                }
            ]
        }
    }

    Rectangle {
        id: rectangle__status_bar
        width: parent.width
        height: 30
        anchors.top: login_button.bottom
        color: "transparent" //parent.color
        radius: parent.radius
        visible: true
        Text {
            id: text_login_status
            anchors.centerIn: parent
        }
    }

    FilTour {
        id: id_filtour__loginpage
        steps: [
            { title: qsTr("User Name"), description: qsTr("Enter the username of the input file isolator. If you don't have one, please contact the administrator to assign one."), target:()=>id_filtextbox__user },
            { title: qsTr("Password"), description: qsTr("Please enter the password corresponding to your username. If you forget it, please contact the administrator."), target:()=>id_filtextbox__password },
            { title: qsTr("Server"), description: qsTr("Fill in the web access link of the file isolator. Please use the default link unless there are special circumstances."), target:()=>id_filtextbox__weburl },
            { title: qsTr("Login"), description: qsTr("Click the login button to use the web service provided by the file isolator."), target:()=>id_filradiusbuttonn__login }
        ]
    }

    Timer {
        id: id_timer__startTour
        interval: 100
        onTriggered: {
            id_filtour__loginpage.open()
        }
    }

    Timer {
        id: id_timer__autoLogin
        interval: 500
        onTriggered: {
            console.log("onTriggered Auto Login")
            showInfo("Start automatic login")
            if (AppInfo.debugEnable) {
                loginInfoSave()
                loginSucceed()
            } else {
                text_login_status.text = ""
                login(user_name, user_password, user_weburl)
            }
        }
    }

    // 2508012_2143: 参考FluUI的Network逻辑
    NetworkCallable {
        id: id_callable__login
        onStart: {
            id_filradiusbuttonn__login.state = "logging"
        }
        onFinish: {
            id_filradiusbuttonn__login.state = "idle"
        }
        onError: (status, errorString, result) => {
            console.debug(status + ";" + errorString + ";" + result)
        }
        onCache: (result) => {
            console.debug(result)
        }
        onSuccess: (result) => {
            console.debug(result)
            // 尝试获取<div style="width:33%; float:left;" id="sessionUsername">当前用户: zhangsan</div> => 'zhangsan'
            var website_user = extractUsername(result)
            console.debug("Get Website UserName[%1]: %2".arg(website_user.length).arg(website_user))
            if (website_user.length > 0) {
                text_login_status.text = ""
                loginInfoSave()
                loginSucceed()
            } else {
                // 尝试获取web返回的错误消息
                var msg = extractDivContent(result, "msg")
                if (msg.length > 0) {
                    console.warn("Login Error: ", msg)
                    text_login_status.text = msg
                }
            }
        }
    }
    // 从返回的html结果中获取当前用户
    function extractUsername(htmlString) {
        var pattern = /当前用户:\s*([^<]*)\s*<\/div>/;
        var match = htmlString.match(pattern);
        return match ? match[1].trim() : "";
    }
    // 通过class name获取标签信息
    function extractDivContent(htmlString, className) {
        var pattern = new RegExp('<div class="' + className + '">([^<]*)<\/div>');
        var match = htmlString.match(pattern);
        return match ? match[1].trim() : "";
    }
    function extractErrorMessage(htmlString) {
        var pattern = /<div class="msg">([^<]*)<\/div>/;
        var match = htmlString.match(pattern);
        return match ? match[1].trim() : "";
    }
    // 登录成功后保存密码
    function loginInfoSave() {
        SettingsHelper.saveUserName(user_name)
        if (checkbox_group.savePassword) {
            SettingsHelper.saveUserPassword(user_password)
        } else {
            SettingsHelper.saveUserPassword("")
        }
        SettingsHelper.saveWebUrl(user_weburl)
        SettingsHelper.saveSavePassword(checkbox_group.savePassword)
        SettingsHelper.saveAutoLogin(checkbox_group.saveAutoLogin)
    }
    // 登录函数
    function login(username, password, url) {
        if (typeof username !== "string" || typeof password !== "string" || typeof url !== "string") {
            console.warn("Invalid string format, please check it.")
            return
        }
        if (username.length <= 0 || password.length <= 0 || url.length <= 0) {
            console.warn("Invalid string length, abort login. [%1,%2,%3]"
                         .arg(username.length)
                         .arg(password.length)
                         .arg(url.length))
            return
        }
        // start request webssite
        var request_url = url + "/index.php?user/loginSubmit&name=%1&check_code=undefined&password=%2&rember_password=0".arg(username).arg(password)
        // var request_url = "https://www.baidu.com"

        console.log("url=" + request_url)
        Network.get(request_url)
        .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0")
        .bind(control)
        .go(id_callable__login)
    }
    // 初始化文本输入框
    Component.onCompleted: {
        console.log("Component.onCompleted")
        loadSettingsConfig()
        // auto login
        if (checkbox_group.saveAutoLogin === true) {
            id_timer__autoLogin.restart()
        }
        loadTour() // To stop Auto Login timer if load tour succeed.
    }

    function loadSettingsConfig() {
        console.log("loadSettingsConfig")
        id_filtextbox__user.text     = SettingsHelper.getUserName()
        id_filtextbox__password.text = SettingsHelper.getUserPassword()
        id_filtextbox__weburl.text   = SettingsHelper.getWebUrl()
        checkbox_group.savePassword  = SettingsHelper.getSavePassword()
        checkbox_group.saveAutoLogin = SettingsHelper.getAutoLogin()
    }

    // 参考Qt助手文档编写，获取不到数据特别长的cookie数据，预计在未来的版本中废除
    function login1(username, password, url) {
        if (typeof username !== "string" || typeof password !== "string" || typeof url !== "string") {
            console.warn("Invalid string format, please check it.")
            return
        }
        if (username.length <= 0 || password.length <= 0 || url.length <= 0) {
            console.warn("Invalid string length, abort login. [%1,%2,%3]"
                         .arg(username.length)
                         .arg(password.length)
                         .arg(url.length))
            return
        }
        // start request website
        let request = new XMLHttpRequest();
        request.open("GET", "https://www.baidu.com")
        request.onreadystatechange = function() {
            console.log("request.readyState=%1".arg(request.readyState))
            if (request.readyState === XMLHttpRequest.DONE) {
                let response = {
                    status: request.status,
                    headers: request.getAllResponseHeaders(),
                    contentType: request.responseType,
                    content: request.response
                }
                var cookie = request.getResponseHeader("Set-Cookie")
                console.log("Received Cookie:", cookie)
                console.log("response.status=%1".arg(response.status))
                // console.log("response.content=%1".arg(response.content))
                var headers = request.getAllResponseHeaders()
                console.log("All headers:", headers)
                var cookieHeader = headers.match(/^Set-Cookie:\s*([^;]*)/mi);
                if (cookieHeader) {
                    console.log("Cookie:", cookieHeader[1]);
                }
            } else if (request.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
                // var headers = request
            }
        }
        request.withCredentials = true;
        request.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0")
        request.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
        request.setRequestHeader("Accept-Encoding", "gzip, deflate, br, zstd")
        // request.setRequestHeader("Content-Type", "application/json")
        request.send()
    }

    // 自动加载漫游式引导
    function loadTour() {
        if (AppInfo.debugEnable) {
            console.log("loadTour debugEnable, not load tour")
            return
        }
        if (!TourTools.readRecord(objectName)) {
            console.log("loadTour to stop auto login timer")
            id_timer__autoLogin.stop()
            id_timer__startTour.restart()
            TourTools.addRecord(objectName)
        }
    }
}
